import React, {
  MutableRefObject,
  RefObject,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useReducer,
  useRef,
  useState,
} from 'react';
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';
import { Button, Checkbox, ConfigProvider, message, PaginationProps, Row, Space } from 'antd';
import { hasAuth } from '@inbiz/basic/AuthForm';
import { useModelList } from '@inbiz/hooks';
import { InBizTableCtx, InBizTableRefCtx } from './context';
import { useTreeNode, TextWidget, getMessage, useGetMessage } from '@inbiz/react';
import Actions from './preview/web/Actions';
import { getOfficialPreview, InbizIcon, useApp } from '@inbiz/utils';
import cls from 'classnames';
import formatters from './formatters';
import {
  ActionEnum,
  arrIsEmpty,
  ColumnConst,
  EventsMap,
  InlineDefaultActions,
  ResConst,
  UnitEnum,
} from './shared';
import { loadDetail } from '@inbiz/render';
import { ColumnsType, ColumnType } from 'antd/lib/table/interface';
import {
  ActionConfigType,
  ActionProps,
  ModalConfig,
  PageData,
  PropConfigType,
  QueryParams,
  RecordType,
  TitleConfig,
  ToolbarType,
  VisibleColumnType,
} from './interfaces';

/**
 * 分页hook：初始化一些参数
 * @param config antd 表格配置属性
 */
export const usePagination = (config: PaginationProps): PaginationProps => {
  return {
    current: 1,
    pageSize: 999,
    defaultPageSize: 999,
    defaultCurrent: 1,
    showSizeChanger: false,
    showTotal: (total: number) => `共 ${total} 条`,
    ...config,
  };
};

/**
 * 平铺表格配置属性
 */
export const useColumnConfig = () => {
  const { columnConfig, inbiz } = useContext(InBizTableCtx);
  const { tableValues, formItems = {}, queryFields = [], auth } = columnConfig || {};
  const { attrs, actions = [], subWindow = [] } = tableValues || {};
  return {
    formItems,
    attrs,
    actions,
    subWindow,
    queryFields,
    auth,
    inbiz,
  };
};

/**
 * 获取表格配置
 */
export const useFormItems = () => {
  const { formItems = {} } = useColumnConfig();
  return formItems;
};

/**
 * 处理表头操作按钮配置
 */
export const useToolbar = (props:any): ToolbarType | undefined => {
  const { columnConfig } = useContext(InBizTableCtx);
  const { tableValues, formItems = {} } = columnConfig || {};
  const { actions } = tableValues || {};
  return useMemo(() => {
    if (arrIsEmpty(actions)) {
      return;
    }
    let buttons = (actions as ActionProps[])?.filter(item => item.show || item.show == undefined).filter((action) => {
      // let buttons = (actions as ActionProps[])?.filter((action) => {
      if (action.actionType === ActionEnum.customColumn) {
        return false;
      }
      if (
        (action.position === 'tableHeader' && !InlineDefaultActions.includes(action.actionType)) ||
        (!action.position &&
          !InlineDefaultActions.includes(action.actionType) &&
          action.actionType !== ActionEnum.del)
      ) {
        if (
          action.actionType &&
          [ActionEnum.save, ActionEnum.add, ActionEnum.saveAndNew].includes(
            action.actionType as ActionEnum,
          )
        ) {
          action.buttonType = 'primary';
        }
        return true;
      }
      return false;
    });
    if(
      props.readOnly
    ){
      buttons = buttons.filter(item => {
        if(
          item.actionType == ActionEnum.custom
        ){
          return true;
        }
      })
    }
   
    
    return {
      actions: buttons,
      displayQty: Number(formItems?.toolbarDisplayQty || 3),
      // actionDisplaySetup: formItems?.actionDisplaySetup,
      inLineBtnShow: formItems?.inLineBtnShow,
      tableHeaderBtnShow: formItems?.tableHeaderBtnShow,
    };
  }, [actions, formItems]);

};
/**
 * 处理弹窗配置
 */
export const useModalConfig = (): ModalConfig => {
  const { actions, subWindow, formItems } = useColumnConfig();

  return useMemo(() => {
    const { width, height } = formItems || {};
    const { widowWidth = 60, widthSuffix = '%' } = width || {};
    const { windowHeight = 60, heightSuffix = '%' } = height || {};
    const modalWidth = widthSuffix === '%' ? `${widowWidth}${widthSuffix}` : widowWidth;
    const modalHeight = heightSuffix === '%' ? `${windowHeight}${heightSuffix}` : windowHeight;
    const actionObj =
      actions?.reduce((obj, cur) => {
        if (cur) {
          obj[cur.actionType] = cur;
        }
        return obj;
      }, {}) || {};
    return {
      actions: (subWindow as ActionConfigType[])?.map((subAction) => {
        const parent = subAction?.parentAction ? actionObj?.[subAction?.parentAction] : null;
        if (!parent) {
          return subAction;
        }
        return {
          ...subAction,
          page: parent.page,
          windowName: parent.windowName || parent.actionName,
          openMode: parent.openMode,
        };
      }),
      width: modalWidth,
      height: modalHeight,
    };
  }, [subWindow, actions, formItems]);
};

/**
 * 获取表格列总宽度
 * @param columns 表格列
 */
export const useColumnsWidth = (columns?: ColumnsType<RecordType>) => {
  return useMemo(
    () =>
      columns?.reduce((sum, col) => {
        if (col.width) {
          return sum + (col.width as number);
        }
        return sum;
      }, 0) || 0,
    [columns],
  );
};

export const percentageWidthCount = (
  tableWidth: number,
  rowSelection: any,
  columns?: ColumnsType<RecordType>,
  resizedWidth?: RefObject<{ [key: string]: number }>,
) => {
  const totalWidth = rowSelection ? tableWidth - 100 : tableWidth - 50;
  const actionCol = columns!.find(
    (column: ColumnType<RecordType>) => column.dataIndex === ColumnConst.actions,
  );
  let attrsWidth = 0;
  columns!.forEach((column: ColumnType<RecordType>) => {
    if (column.dataIndex !== ColumnConst.index && column.dataIndex !== ColumnConst?.actions) {
      attrsWidth += Number(column.width);
    }
  });
  return columns!.map((column: ColumnType<RecordType>) => {
    column.fixed = undefined;
    if (column.dataIndex === ColumnConst.index || column.dataIndex === ColumnConst.actions) {
      return column;
    }
    const width = resizedWidth?.current?.[column.dataIndex as string] || column.width;
    return {
      ...column,
      width: Math.floor(
        ((actionCol ? totalWidth - Number(actionCol.width) : (totalWidth as number)) / attrsWidth) *
        Number(width),
      ),
    };
  });
};

/**
 * 处理表格在百分比和像素下的列宽度
 * @param tableWidth 表格总宽度
 * @param totalWidth 表格列总宽度
 * @param columns 表格列
 */
export const useColumns = (
  tableWidth: number,
  totalWidth: number,
  columns?: ColumnsType<RecordType>,
  resizedWidth?: RefObject<{ [key: string]: number }>,
) => {
  const { rowSelection } = useContext(InBizTableCtx);
  const { widthUnit: unit } = useFormItems();
  return useMemo(() => {
    if (!columns) {
      return [];
    }
    const actionCol = columns.find(
      (column: ColumnType<RecordType>) => column.dataIndex === ColumnConst.actions,
    );
    if (unit === UnitEnum.percentage) {
      return percentageWidthCount(tableWidth, rowSelection, columns, resizedWidth);
    }

    if (actionCol && totalWidth <= tableWidth) {
      actionCol.width = (actionCol.fixed as string) === 'none' ? undefined : actionCol.width;
      if (columns.length > 2 && actionCol.width) {
        const lastColIdx = actionCol.fixed === 'right' ? columns.length - 2 : columns.length - 1;
        columns[lastColIdx].width = undefined;
      }
    }
    return columns;
  }, [tableWidth, totalWidth, columns]);
};

/**
 * 判断是否为设计器模式下
 */
export const useIsDesigner = () => {
  return !!useTreeNode();
};

/**
 * 初始化查询分页参数
 */
export const useInitSearchRef = () => {
  const { searchRef } = useContext(InBizTableRefCtx);
  const formItems = useFormItems();
  useMemo(() => {
    searchRef.current = {
      ...searchRef.current,
      pageInfo: {
        current: 1,
        pageSize: formItems.pageSize || 30,
      },
    };
  }, []);
};

/**
 * 设置表格横向滚动
 * @param tableWidth
 * @param totalWidth
 */
export const useScrollX = (tableWidth: number, totalWidth: number) => {
  const { widthUnit: unit } = useFormItems();
  return useMemo(
    () => (unit === UnitEnum.pixel && totalWidth > tableWidth ? 'max-content' : undefined),
    [tableWidth, totalWidth],
  );
};

/**
 *
 * @param pagination
 * @param columns
 */
export const useIndex = (
  pagination: { currentPage: number; pageSize: number },
  columns?: ColumnsType<RecordType>,
) => {
  return useMemo(() => {
    if (arrIsEmpty(columns)) {
      return;
    }
    const index = columns?.find(
      (col) => (col as ColumnType<RecordType>).dataIndex === ColumnConst.index,
    );
    if (!index) {
      return;
    }
    index.render = (text, record, rowIdx) => {
      return (
        pagination.currentPage &&
        `${rowIdx + 1 + (pagination.currentPage - 1) * (pagination.pageSize || 10)}`
      );
    };
  }, []);
};

/**
 * 格式化导出字段
 */
export const useExportFields = () => {
  const { attrs } = useColumnConfig();
  return attrs
    ?.filter((col: PropConfigType) => (col as VisibleColumnType).visible !== '0' && col.width)
    .map((col: any) => {
      return {
        colName: col.columnName,
        proName: col.propName,
      };
    });
};

/**
 * 获取appid
 */
export const useAppId = () => {
  const { inbiz } = useContext(InBizTableCtx);
  return inbiz?.appInfo?.appId;
};

/**
 * 拖拽改变列宽
 * @param columns
 * @param handleResize
 */
export const useResize = (
  columns: ColumnType<RecordType>[],
  handleResize: (idx: number) => (e: any, { size }: any) => void,
  viewMode?: string
) => {
  const { resizeColumnWidth } = useContext(InBizTableCtx);
  if (columns && resizeColumnWidth && viewMode != 'look') {
    columns.map((column, index) => {
      column.onHeaderCell = (col: ColumnType<RecordType>) => {
        return {
          dataIndex: col.dataIndex,
          width: col.width,
          onResize: handleResize(index),
          columns: columns,
        };
      };
    });
  }
};

/**
 * 按钮聚合操作
 * @param handlePrint
 * @param tableCacheRef
 * @param modalRef
 */
export const useActionReducer = ({
  tableCacheRef,
  modalRef,
}: {
  attrs?: PropConfigType[];
  tableCacheRef: MutableRefObject<any>;
  modalRef: MutableRefObject<any>;
  // handlePrint: () => void;
}) => {
  const { emit, selectComponent, inbiz, inlineEdit, columnConfig } = useContext(InBizTableCtx);
  const { eventsRef, pageRef, searchRef } = useContext(InBizTableRefCtx);

  const changeParentStatus = () => {
    if (selectComponent) {
      const parentIdString = tableCacheRef.current.dataSetCache.cacheParent;
      inbiz?.(selectComponent).changeDataStatus(parentIdString);
    }
  };

  const onSave = useCallback(async (type:string) => {
    const { code, values } = await pageRef.current!.page.validateSubmitData();
    if (code === 0) {
      const anotherNameMap = tableCacheRef.current.anotherNameMap;
      Object.entries(anotherNameMap).forEach(([key, value]) => {
        if (key !== value && values['masterDatas']?.hasOwnProperty(value)) {
          values['masterDatas'][key] = values['masterDatas'][value];
          values['masterDatas'][value] = null;
        }
      });
      // 操作前拦截
      const result = await eventsRef.current.onBeforeOperationAsync?.(type, values);
      if (result === false) {
        return ''
      } else {
        const newValues = await eventsRef.current.onModalSaveModify?.(values, pageRef.current!.page)
        pageRef.current!.page.reset();
        let res = tableCacheRef.current.dataSetCache.changeCache(newValues || values);
        changeParentStatus();
        return res;
      }
    }
    return Promise.reject(code);
    // return pageRef.current!.page.submit(false);
  }, []);

  const getRow = (dataSource: RecordType[], id: number, isPre?: boolean) => {
    if (!dataSource) {
      return;
    }
    const primaryKey = tableCacheRef.current?.dataSetCache?.primaryKey;
    const curInx = dataSource.findIndex((row) => `${row[primaryKey]}` === `${id}`);
    return dataSource[isPre ? curInx - 1 : curInx + 1];
  };
  const nope = () => { };
  const reducer = useCallback(async (state: any, action: any): Promise<any> => {
    const { actionType } = action;
    action.title = action.windowName || action.actionName;
    await nope();

    switch (actionType) {
      case ActionEnum.add: {
        if (tableCacheRef.current.hasError) {
          return {};
        }
        if (tableCacheRef.current.dataSetCache.cacheParent || !selectComponent) {
          tableCacheRef.current.dataSetCache.cacheStatus(ActionEnum.add, action.data);
          if (inlineEdit && action.openMode !== 'modal') {
            tableCacheRef.current.dataSetCache.changeCache({});
            changeParentStatus();
            tableCacheRef.current.loadCacheData(ActionEnum.add);
          } else {
            modalRef.current.showModal(true);
          }
        } else {
          message.warning(getMessage('SubTable.message.parentRequire'));
        }

        return {
          ...action,
          openMode: inlineEdit && action.openMode !== 'modal' ? action.openMode : 'modal',
        };
      }
      case ActionEnum.edit: {
        if (!tableCacheRef.current.hasError) {
          await tableCacheRef.current.saveEditInline();
          tableCacheRef.current.dataSetCache.cacheStatus(ActionEnum.edit, action.data);
          modalRef.current.showModal(true);
        }

        return action;
      }
      case ActionEnum.view: {
        if (!tableCacheRef.current.hasError) {
          await tableCacheRef.current.saveEditInline();
          modalRef.current.showModal(true);
        }

        return action;
      }
      case ActionEnum.save:
        return onSave(ActionEnum.save)
          .then((res: any) => {
            (emit as any)?.(EventsMap.onClose);
            modalRef.current.showModal(false);
            if (!res) {
              return false
            }
            tableCacheRef.current.loadCacheData(res, true);
            // tableCacheRef.current.refresh();
            return {
              ...action,
              data: {
                // ...res?.modelValue?.masterDatas,
                id: undefined,
              },
            };
          })
          .catch((err: any) => {
            return Promise.reject(err);
          });
      case ActionEnum.saveAndNew: {
        return onSave(ActionEnum.saveAndNew)
          .then(async (res: any) => {
            if (!res) {
              return false
            }
            tableCacheRef.current.loadCacheData(res);
            // tableCacheRef.current.refresh();
            // resetForm();
            // const old = await state;
            tableCacheRef.current.dataSetCache.cacheType = 'changeCacheAdd';
            return {
              ...action,
              data: {
                // ...res?.modelValue?.masterDatas,
                id: undefined,
              },
            };
          })
          .catch((err: any) => {
            return Promise.reject(err);
          });
      }
      case ActionEnum.pre: {
        let curRow = (await state)?.data;
        const primaryKey = tableCacheRef.current?.dataSetCache?.primaryKey;
        const pre = getRow(tableCacheRef.current.data, curRow?.[primaryKey], true);
        if (!pre) {
          message.warning(getMessage('SubTable.message.noPrevData'));
          return {
            ...action,
            data: curRow,
          };
        }
        return {
          ...action,
          data: pre,
        };
      }
      case ActionEnum.next: {
        let curRow = (await state)?.data;
        const primaryKey = tableCacheRef.current?.dataSetCache?.primaryKey;
        const next = getRow(tableCacheRef.current.data, curRow?.[primaryKey], false);
        if (!next) {
          message.warning(getMessage('SubTable.message.noNextData'));

          return {
            ...action,
            data: curRow,
          };
        }
        return {
          ...action,
          data: next,
        };
      }
      case ActionEnum.del: {
        const primaryKey = tableCacheRef.current?.dataSetCache?.primaryKey;
        tableCacheRef.current.dataSetCache.cacheStatus(ActionEnum.del, action.data);
        if (!action.data?.[primaryKey] && arrIsEmpty(tableCacheRef.current.keyList)) {
          message.warning(getMessage('SubTable.message.deleteChoosed'));
          return ResConst.other;
        }
        tableCacheRef.current.delChildrenAdd(action.data);
        tableCacheRef.current.dataSetCache.changeCacheDelete();
        return tableCacheRef.current.loadCacheData(ActionEnum.del);
      }
      case ActionEnum.cancel: {
        (emit as any)?.(EventsMap.onClick, 'cancel');
        Promise.resolve(eventsRef?.current.onBeforeClose?.() ?? true).then((res) => {
          modalRef.current.showModal(!res);
          if (!res) {
            return;
          }
          (emit as any)?.(EventsMap.onClose);
        });

        return {
          data: {
            id: undefined,
          },
        };
      }
    }
  }, []);
  // @ts-ignore
  const [state, dispatch] = useReducer(reducer, undefined);

  return [state, dispatch];
};

export const useTitle = (title: any) => {
  return useMemo(() => {
    if (typeof title === 'object') {
      return (title as TitleConfig).status ? () => (title as TitleConfig).value : undefined;
    }
    return title;
  }, [title]);
};

export const usePrefixCls = (
  tag?: string,
  props?: {
    prefixCls?: string;
  },
) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  if (getPrefixCls) {
    return getPrefixCls(tag, props?.prefixCls);
  } else {
    const prefix = props?.prefixCls ?? 'ant-';
    return `${prefix}${tag ?? ''}`;
  }
};

/**
 * 拼接样式inbiz前缀
 * @param tag 组件名字
 *
 */
export const useInbizPrefixCls = (tag?: string, prefixCls?: string) => {
  const prefix = prefixCls ?? 'inbiz-';
  return `${prefix}${tag ?? ''}`;
};

/**
 * 请求数据，拼装参数
 */
export const useFetchData = () => {
  const { emit, sourceModel } = useContext(InBizTableCtx);
  const { searchRef, eventsRef, firstRequestRef } = useContext(InBizTableRefCtx);
  const { runAsync, loading: realLoading } = useModelList(eventsRef);
  const [loading, $loading] = useState(false);
  const [pageData, setPageData] = useState<PageData>({});
  const appId = useAppId();

  const fetchData = useCallback((query?: QueryParams, cache?: any) => {
    const { pageInfo, orders, conditions } = query || {};
    if (!sourceModel || !appId) {
      return;
    }
    const newParam = {
      appId: appId,
      key: sourceModel,
      pageInfo: {
        index: pageInfo?.current || searchRef.current.pageInfo!.current,
        size: pageInfo?.pageSize || searchRef.current.pageInfo!.pageSize,
      },
      orderInfo: orders || searchRef.current.orders,
      conditions: formatters.filterCondition(conditions || searchRef.current.conditions),
    };
    $loading(true);
    const promise = Promise.resolve(newParam);
    return (
      promise
        .then((res) => {
          if (res && res.conditions.length !== 0) {
            return runAsync(newParam);
          }
          return { Total: cache.pageTotal };
        })
        //@ts-ignore
        .then((res: { Rows: RecordType[]; Success: number; Total: number; primary?: string }) => {
          // const data = res.Rows?.map((originData) => {
          //   return {
          //     ...(cache?.getQueryMapData(restProps) || restProps),
          //   };
          // });
          const data = cache?.getQueryMapData(res.Rows ?? []);
          // const cacheData = cache?.getRangeArray() || [];
          if (data) {
            // window.setTimeout(() => {
            setPageData({
              data: [...data],
              total: res.Total,
              primary: res.primary ?? 'id',
              relationField: res.RelationField,
              // primary:'lastmodifierid'
            });
            $loading(realLoading);
            // }, 350);
          } else {
            // window.setTimeout(() => {
            setPageData({
              data: [],
              total: res.Total,
              primary: res.primary ?? 'id',
              relationField: res.RelationField,
            });
            $loading(realLoading);
            // }, 350);
          }

          if (firstRequestRef.current) {
            (emit as any)?.(EventsMap.onload);
            firstRequestRef.current = false;
          }
          (emit as any)?.(EventsMap.onSuccess, data);
          return {
            data: [...data],
            primary: res.primary ?? 'id',
            relationField: res.RelationField,
          };
        })
        .catch((err) => {
          (emit as any)?.('onError', err.message);
        })
        .finally(() => {
          $loading(realLoading);
        })
    );
  }, []);

  return {
    loading,
    fetchData,
    pageData,
    setPageData,
  };
};

/**
 * 格式化表格操作列配置
 */
export const useFormatInnerActions = () => {
  const { actions } = useColumnConfig();

  return (actions as ActionProps[])?.filter((action) => {
    if (action.actionType === ActionEnum.customColumn) {
      return false;
    }
    if (
      action.position === 'inline' ||
      InlineDefaultActions.includes(action.actionType) ||
      (action.position !== 'tableHeader' && action.actionType === ActionEnum.del)
    ) {
      action.buttonType = 'link';
      return true;
    }
    return false;
  });
};

const SortNode = (status, isCurrentColumn) => {
  return (
    <span className="ant-table-column-sorter">
      <span className="ant-table-column-sorter-inner">
        <CaretUpOutlined
          title={getMessage('SubTable.sorter.ascend')}
          className={cls('ant-table-column-sorter-up', {
            active: status === 'ascend' && isCurrentColumn,
          })}
        />
        <CaretDownOutlined
          title={getMessage('SubTable.sorter.descend')}
          className={cls('ant-table-column-sorter-down', {
            active: status === 'descend' && isCurrentColumn,
          })}
        />
      </span>
    </span>
  );
};

/**
 * 格式化表格列(非行内编辑)
 */
export function useFormatColumns(): ColumnsType<RecordType> {
  const { align, showLineNumber, emit, readOnly,viewMode } = useContext(InBizTableCtx);

  const { actions, attrs, formItems, auth, inbiz } = useColumnConfig();
  const { eventsRef } = useContext(InBizTableRefCtx);
  const _intl = useGetMessage('SubTable');
  const intlComponent = (key: string) => {
    const middle = _intl((key ?? '').replace(/SubTable\./g, ''));
    if ((middle ?? '').indexOf('SubTable') >= 0) {
      return (middle ?? '').replace(/SubTable\./g, '');
    }
    return middle;
  };
  const innerActions = useFormatInnerActions();
  if (!attrs) {
    return [];
  }
  const cols = attrs
    .filter((col) => (col as VisibleColumnType).visible !== '0' && col.width)
    .map((col) => {
      const colTitle =
        col.columnName ||
        (col.propName?.includes('$') ? col.propName.replace('$', '.') : col.propName);
      return {
        title: () => {
          return (
            <span title={getMessage(colTitle)}>
              <TextWidget>{colTitle}</TextWidget>
            </span>
          );
        },
        dataIndex: col.propName,
        width: col.width,
        sorter: col.sorter === 'on',
        fixed: col.fixed === 'none' ? false : col.fixed,
        ellipsis: true,
        align: align,
        className: 'inbiz-table-cell',
        render: (value, record, index) => {
          return eventsRef?.current.onColumnsFormat?.(value, record, index, col.propName) ?? value;
        },
      } as ColumnType<RecordType>;
    });
  const addActions = () => {
    const actionIndex = cols.findIndex((col) => col.dataIndex === ColumnConst.actions);
    if (actionIndex > -1) {
      cols?.splice(actionIndex, 1);
    }
    const actions = (eventsRef?.current.onOperateColumnFormat?.(innerActions) ??
      innerActions) as ActionConfigType[];
    const leftActions = actions?.map((ele) => {
      return {
        ...ele,
        ...hasAuth(
          {
            table: [{ ...ele, operationType: ele.actionType }],
            auth: auth,
          },
          ele.actionType,
          inbiz?.auth,
        ),
      };
    });
    const leftAuthActions = leftActions?.filter((ele) => ele.auth).filter(item => {
      if (readOnly) {
        return item.actionType != 'edit' && item.actionType != 'del'
      } else {
        return true
      }
    });
    const actionCol: ColumnType<RecordType> = {
      title: intlComponent('column.action'),
      // title: () => <TextWidget>SubTable.column.action</TextWidget>,
      dataIndex: ColumnConst.actions,
      width: formItems?.actionColumnWidth || 200,
      fixed: formItems?.fixedActionColumn === 'none' ? false : formItems?.fixedActionColumn,
      className:'actions inbiz-table-cell',
      ellipsis: true,
      render: (_: any, row: any, index) => {
        const ActionsList =
          eventsRef?.current?.onOperateFormat?.(row, index, leftAuthActions) || leftAuthActions;
        if (typeof ActionsList === 'function') {
          return <ActionsList row={row} index={index} actions={actions} emit={emit} />;
        }
        if (typeof ActionsList === 'string') {
          return ActionsList;
        }
        return <Actions data={row} actions={ActionsList} />;
      },
    };
    
      if (leftAuthActions && leftAuthActions.length > 0 &&(viewMode!='look')) {
        formItems?.fixedActionColumn === 'left' ? cols?.unshift(actionCol) : cols?.push(actionCol);
      }
  
  
  };

  const formatLineNumber = () => {
    const removeLineNumber = () => {
      return cols.filter((col) => col.dataIndex !== ColumnConst.index);
    };
    const addLineNumber = () => {
      cols.unshift({
        title: intlComponent('column.index'),
        // title: () => <TextWidget>SubTable.column.index</TextWidget>,
        width: 50,
        dataIndex: ColumnConst.index,
        fixed: 'left',
        ellipsis: true,
        className: 'index inbiz-table-cell',
      });
    };
    return showLineNumber ? addLineNumber() : removeLineNumber();
  };

  formatLineNumber();
  addActions();

  const getFilterProps = (): ColumnType<RecordType> => {
    const getFilters = () => {
      if (!actions?.find((action) => action.actionType === ActionEnum.customColumn)) {
        return;
      }
      return attrs.reduce((filters: { value: any; label: any }[], attr) => {
        if ((attr as VisibleColumnType).visible === '0' || !attr.width || attr.fixed) {
          return filters;
        }
        const label =
          attr.columnName ||
          (attr.propName?.includes('$') ? attr.propName.split('$').pop() : attr.propName);
        filters.push({
          label: label,
          value: attr.propName,
        });
        return filters;
      }, []);
    };
    const filters = getFilters();
    const defaultFilteredValue = filters?.map((filter) => filter.value);
    return {
      filterDropdown: filters
        ? ({ selectedKeys, setSelectedKeys, confirm }) => {
          return (
            <Space direction="vertical" className="inbiz-table-custom-columns">
              <Checkbox.Group
                value={selectedKeys}
                onChange={(value) => setSelectedKeys(value as React.Key[])}
              >
                {filters?.map((filter) => (
                  <Row key={filter.value}>
                    <Checkbox value={filter.value}>{filter.label}</Checkbox>
                  </Row>
                ))}
              </Checkbox.Group>
              <Space size="large">
                <Button
                  type="link"
                  onClick={() => {
                    setSelectedKeys(
                      Array.isArray(defaultFilteredValue) ? defaultFilteredValue : [],
                    );
                    confirm({ closeDropdown: true });
                  }}
                  size="small"
                >
                  <TextWidget>SubTable.button.reset</TextWidget>
                </Button>
                <Button
                  size="small"
                  type="primary"
                  onClick={() => {
                    confirm({ closeDropdown: true });
                  }}
                >
                  <TextWidget>SubTable.button.makeSure</TextWidget>
                </Button>
              </Space>
            </Space>
          );
        }
        : undefined,
      defaultFilteredValue,
      filterIcon: filters && <InbizIcon type="icon-ic-setting" />,
    };
  };

  const fixedLeft = cols.filter((col) => col.fixed === 'left');
  const rightLeft = cols.filter((col) => col.fixed === 'right');
  const unfixed = cols.filter((col) => !col.fixed);
  const all = [...fixedLeft, ...unfixed, ...rightLeft];
  let last = all.pop();
  last = {
    ...last,
    ...getFilterProps(),
  };
  return [...all, last].map((ele) => ({
    ...ele,
    showSorterTooltip: false,
    title: ({ sortOrder, sortColumn, filters }) => {
      let titleEle: any = typeof ele.title === 'string' ? ele.title : ele.title?.();
      return (
        <div className="antd-self-sort-wrap">
          {titleEle}
          {ele.sorter && SortNode(sortOrder, ele.dataIndex === sortColumn?.dataIndex)}
        </div>
      );
    },
    //@ts-ignore
    onCell: (record, rowIndex) => ({
      dataIndex: ele.dataIndex,
      rowIndex,
      record,
    }),
  }));
}

export const useGetChild = () => {
  const { inbiz, controlId } = useContext(InBizTableCtx);
  const childRef = useRef<Array<string>>([]);
  useEffect(() => {
    //@ts-ignore
    const fields = inbiz?.getFields() ?? [];
    fields.forEach((ele: any) => {
      if (ele.componentProps.selectComponent === controlId) {
        childRef.current.push(ele.componentProps.controlId);
      }
    });
  }, []);

  return childRef.current;
};

export const usegetPageDetail = () => {
  const { columnConfig } = useContext(InBizTableCtx);
  //@ts-ignore
  const appInfo: any = inbizGlobal?.appInfo || useApp();
  const [schema, $schema] = useState({
    schema: {},
    keysMap: {},
    form: {},
    routeId: '',
    contorIdToAttr: {},
  });
  const actionList = columnConfig?.tableValues?.actions ?? [];
  const route = actionList.filter((ele) => ele.actionType === 'add')[0]?.page ?? '';
  useEffect(() => {
    loadDetail({
      //@ts-ignore
      siteOutId: appInfo?.SiteInfo?.OutId,
      //@ts-ignore
      dataVersionId: appInfo?.SiteInfo?.DataVersionId,
      route: (route.split(',')[0] ?? '').replace('page/', ''),
      appId: appInfo?.AppId,
      isOfficialPreview: getOfficialPreview(),
      isAuth: true, // 权限存在的时候不请求权限
    }).then((res) => {
      const { properties = {} } = res.schema || {};
      const keys = Object.keys(properties);
      const keysMap = {};
      const contorIdToAttr = {};
      keys.forEach((ele) => {
        let type = properties?.[ele]?.['x-component-props']?.['model']?.['Name'];
        let typeEnd = properties?.[ele]?.['x-component-props']?.['modelend']?.['Name'];
        if (type) {
          keysMap[type] = ele;
          contorIdToAttr[ele] = type;
        }
        if (typeEnd) {
          keysMap[typeEnd] = ele;
          contorIdToAttr[ele] = typeEnd;
        }
      });
      $schema({
        schema: res.schema,
        contorIdToAttr,
        keysMap,
        form: res.form,
        routeId: route.split(',')[1] ?? new Date().valueOf(),
      });
    });
  }, []);

  return [schema];
};
